<template>
    <div class="app-container">
        <el-steps :active="active" finish-status="success">
            <el-step title="商品的基本信息"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品的SKU信息"></el-step>
        </el-steps>


    <!-- 商品基本信息 -->
    <el-row v-show="active == 1">
      <el-col :span="16" :offset="4">
        <el-form ref="form" label-width="120px">
          <el-form-item label="商品标题">
            <el-input v-model="entity.goods.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="商品副标题">
            <el-input  v-model="entity.goods.caption"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select placeholder="请选择一级分类"  v-model="entity.goods.category1Id">
               <el-option v-for="cat  in  cat1" :label="cat.name" :value="cat.id"></el-option>
            </el-select>
            <el-select placeholder="请选择二级分类"  v-model="entity.goods.category2Id">
              <el-option v-for="cat  in  cat2" :label="cat.name" :value="cat.id"></el-option>
            </el-select>
            <el-select placeholder="请选择三级分类" v-model="entity.goods.category3Id">
              <el-option v-for="cat  in  cat3" :label="cat.name" :value="cat.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品模板">
            <el-input disabled  v-model="entity.goods.typeTemplateName"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌">
            <el-select placeholder="请选择品牌" v-model="entity.goods.brandId">
                 <el-option v-for="brand in brandArr" :label="brand.name" :value="brand.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商城价">
            <el-input-number
               v-model="entity.goods.price"
              :precision="2"
              :step="0.1"
              :max="9999"
            ></el-input-number>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="active = 2">下一步,添加商品图片</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>


     <!-- 商品图片 -->
    <el-row v-show="active == 2">
      <el-button @click="addImgBtn()">添加图片</el-button>
      <el-col :span="16" :offset="4">
        <el-table :data="imgsList">
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img style="width:100px;height:80px":src="scope.row" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="delImg(scope.$index)" type="primary" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-button type="primary" @click="active = 1">上一步,添加商品的基本信息</el-button>
        <el-button type="primary" @click="active = 3">下一步,添加商品的sku信息</el-button>

        <!-- 添加图片dialog -->
        <el-dialog
          title="添加图片"
          :visible.sync="imageDialogVisible"
          :close-on-click-modal="false"
        >
          <el-form ref="brandForm">
            <el-form-item label="商品图片" prop="logo">
              <el-upload
                action="http://localhost:8081/upload"
                list-type="picture-card"
                name="headerImage"
                :headers="this.headlers"
                :on-success="uploadSuccess"
                :limit="1"
                ref="imgUpload"
                
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addImg()">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

    
     <!-- sku -->
    <el-row v-show="active == 3">
      <el-col :span="16" :offset="4">
        <div v-for="(spec, index) in specAndOptionsArr">
          <span>{{spec.name}}</span>
          <el-checkbox v-model="opt.isChoose" @change="genSku()" v-for="(opt, index) in spec.options">{{opt.optionName}}</el-checkbox>
        </div>
         <el-table style="width: 100%" border :data="entity.skus">
            <el-table-column prop="num" label="规格信息">
                <template slot-scope="scope">
                    {{scope.row.spec}}
                </template>
            </el-table-column>
            <el-table-column prop="num" label="库存">
                <template slot-scope="scope">
                    <el-input v-model="entity.skus[scope.$index].num"/>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="价格">
                <template slot-scope="scope">
                    <el-input v-model="entity.skus[scope.$index].price"/>
                </template>
            </el-table-column>
            <el-table-column prop="tc" label="提成">
                <template slot-scope="scope">
                    <el-input v-model="entity.skus[scope.$index].tc"/>
                </template>
            </el-table-column>
             <el-table-column prop="tc" label="是否默认">
                <template slot-scope="scope">
                          <el-checkbox
                            v-model="entity.skus[scope.$index].isDefault"
                            ></el-checkbox
                        >
                </template>
            </el-table-column>
         </el-table>
          <br/>
           <el-button type="primary" @click="active = 2">上一步,商品图片信息</el-button>
           <el-button type="primary" @click="saveGoods()">立即保存</el-button>
      </el-col>
    </el-row>

    </div>
</template>
<script>
import {findByParent,findTmpByCatId,findSpecAndOptionByTid,saveGoods} from '@/api/goods'
export default {
    data() {
        return {
            active:1,
            imageDialogVisible:false,  //控制添加图片dialog的显示和隐藏
            imgsList:[],//商品图片列表
            entity:{  //最终提交到后台的json数据
                goods:{price:0},
                skus:[]
            },
            headlers:{},
            cat1:[],
            cat2:[],
            cat3:[],
            brandArr:[],
            imgUrl:'',
            specAndOptionsArr:[]
        }
    },
    methods:{
        findByParent(parentId,flag){
            findByParent(parentId).then(res=>{
                 if(flag == 1){
                      this.cat1 = res;  
                 }
                  if(flag == 2){
                      this.cat2 = res;  
                 }  
                  if(flag == 3){
                      this.cat3 = res;  
                 }     
            })
        },
        uploadSuccess(response, file, fileList){
                //获取图片的url              
                this.imgUrl = response.data
        },
        addImg(){
            this.imgsList.push(this.imgUrl);
            this.imageDialogVisible = false;
        },
        addImgBtn(){
            this.imageDialogVisible  = true;
            
            this.$nextTick(()=>{
               this.$refs.imgUpload.clearFiles();//清空图片
             });
            this.headlers={"token":sessionStorage.getItem("token")}
        },
        delImg(index){
             this.imgsList.splice(index,1)   
        } ,
        genSku(){//生成sku信息
             
             console.log(this.specAndOptionsArr);
             this.entity.skus=[{spec:{},num:10000,price:0,tc:0,isDefault:0}];
             //根据用户勾选的规格信息，动态产生sku列表
             this.specAndOptionsArr.forEach(item=>{
                  //[{spec:{},num:10000,price:0,tc:0,isDefault:0}]    skus
                  //specName="内存"   //options:[2G,4G]
                  //item下面如果没有规格选项，就不要addRow   
                  var flag = false;
                  item.options.forEach(opt =>{
                      if(opt.isChoose ==true){
                          flag = true;
                      }
                  })
                  if(flag == true){
                         this.entity.skus = this.addRow(this.entity.skus,item.name,item.options) 
                         //console.log(item.specName);
                  }
             })
            var flag = false;
            this.specAndOptionsArr.forEach(item=>{
                    item.options.forEach(opt =>{
                        if(opt.isChoose==true){
                             flag = true;   
                        }
                    })
            })


            if(flag ==false){
                this.entity.skus=[];
            }
        },
        addRow(skus,name,options){
            var skusItems = [];
             skus.forEach(row=>{
                   var oldRow = row;
                   options.forEach(opt=>{
                       //console.log(opt);
                       if(opt.isChoose==true){ //如果勾选
                            var newRow = JSON.parse(JSON.stringify(oldRow))
                            //console.log(opt.optionName);
                            newRow.spec[name] = opt.optionName
                            skusItems.push(newRow)
                       }
                   })
             })  
             

            return skusItems;
        } ,
        saveGoods(){

              //处理商品图片
              this.entity.goods.smallPic = JSON.stringify(this.imgsList)
              //处理sku的spec
              this.entity.skus.forEach(sku=>{
                  sku.spec = JSON.stringify(sku.spec)
              })
              this.entity.goods.sellerId=sessionStorage.getItem("token")
              this.entity.skus[0].sellerId=sessionStorage.getItem("token")
               saveGoods(this.entity).then(res=>{
                  if (res.success) {
                    this.$router.push("/goods/goodsList");
                  } else {
                    this.$message({
                      showClose: true,
                      message: res.msg,
                      type: "error",
                    });
                  }
               })
        }  
    },
    created() {
         //请求获取以及分类
         this.findByParent(0,1)
    },
    watch:{
        'entity.goods.category1Id':{
             handler: function(newVal,oldVale) {
                   
                    //请求二级分类
                    this.findByParent(newVal,2);
             }
        },
        'entity.goods.category2Id':{
             handler: function(newVal,oldVale) {
                    
                    //请求三级分类
                    this.findByParent(newVal,3);
             }
        },
        'entity.goods.category3Id':{
             handler: function(newVal,oldVale) {
                 //console.log(newVal)
                 //获取模板
                 var _this = this;  
                 findTmpByCatId(newVal).then(res=>{
                     //console.log(res)
                     //console.log(res.tname)
                       _this.entity.goods.typeTemplateName = res.tname;
                       _this.entity.goods.typeTemplateId = res.tid;

                       //获取品牌信息
                      _this.brandArr = JSON.parse("["+res.brands+"]");
                   
                    //console.log(res.tid);
                      //获取规格和规格选项
                     findSpecAndOptionByTid(res.tid).then(res=>{
                          _this.specAndOptionsArr = res;
                          //console.log(_this.specAndOptionsArr)  
                            _this.$forceUpdate()
                     });
                       //强制刷新
                       _this.$forceUpdate()


                    
                 })
             }
        },
        // 'entity.goods.typeTemplateId':{
        //      handler: function(newVal,oldVale) {
        //          //模板id发生变化，品牌列表也发生变化

        //      }
        // }
    }
}
</script>